import {
  Component,
  Optional,
  Inject,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  HostBinding,
  OnInit,
} from '@angular/core';

import {
  NgModel,
  NG_VALUE_ACCESSOR,
  NG_VALIDATORS,
  NG_ASYNC_VALIDATORS,
} from '@angular/forms';

import { ElementBase } from '../element-base';

@Component({
  selector: 'fui-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.sass'],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: InputComponent,
    multi: true,
  }],
})
export class InputComponent extends ElementBase<string> implements OnInit {
  @HostBinding('class.fui-input') hostClass = true;

  @ViewChild(NgModel, { static: true }) model: NgModel;

  /** Prefix icon. */
  @Input() prefix: string;

  /** Suffix icon. */
  @Input() suffix: string;

  /** Placeholder. */
  @Input() placeholder: string;

  /** Input type. */
  @Input() type = 'text';

  /** Validation error messages. */
  @Input() errorMsgs: string[] = [];

  /** Emit blur event. */
  @Output() blur = new EventEmitter();

  isPassword = false;

  get parsedPlaceholder() {
    return this.placeholder || '';
  }

  constructor(
    @Optional() @Inject(NG_VALIDATORS) validators: Array<any>,
    @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<any>,
  ) {
    super(validators, asyncValidators);
  }

  ngOnInit() {
    if ( this.type === 'password' ) {
      this.isPassword = true;
      this.suffix = 'eye-closed';
    }
  }

  toggleShow() {
    if (this.isPassword && !this.disabled) {
      if (this.type === 'password') {
        this.type = 'text';
        this.suffix = 'eye-open';
      } else {
        this.type = 'password';
        this.suffix = 'eye-closed';
      }
    }
  }

}
